import { useEffect, useRef, useState } from "react";

export function TypeWriter({ sentences, typingSpeed = 100, deletingSpeed = 70, pauseBetween = 2000 }: {
    sentences: string[],
    typingSpeed?: number,
    deletingSpeed?: number,
    pauseBetween?: number
}) {
    const [text, setText] = useState("");
    const [isDeleting, setIsDeleting] = useState(false);
    const [isFadeIn, setIsFadeIn] = useState(false);
    const [sentenceIndex, setSentenceIndex] = useState(0);
    const timerRef = useRef<NodeJS.Timeout>();

    useEffect(() => {
        const type = async () => {
            const currentSentence = sentences[sentenceIndex];
            if (!isDeleting) {
                // 打字效果
                setText(currentSentence.substring(0, text.length + 1));
                if (text === currentSentence) {
                    // 开启打字闪烁效果
                    setIsFadeIn(true);
                    // 打完一句话后暂停一段时间，然后开始删除
                    if (sentences.length > 1)
                        timerRef.current = setTimeout(() => setIsDeleting(true), pauseBetween);
                } else {
                    setIsFadeIn(false);
                    timerRef.current = setTimeout(type, typingSpeed);
                }
            } else {
                // 删除效果
                setText(currentSentence.substring(0, text.length - 1));
                setIsFadeIn(false);
                if (text === "") {
                    // 删除完成后切换到下一句话
                    setIsDeleting(false);

                    setSentenceIndex((prevIndex) => (prevIndex + 1) % sentences.length);
                } else {
                    timerRef.current = setTimeout(type, deletingSpeed);
                }
            }
        };

        timerRef.current = setTimeout(type, isDeleting ? deletingSpeed : typingSpeed);

        // 清除定时器
        return () => clearTimeout(timerRef.current);
    }, [text, isDeleting, sentenceIndex, sentences, typingSpeed, deletingSpeed, pauseBetween]);

    return (
        <div className="inline-block relative top-1/2 l-1/2 w-full text-center my-4">
            <span className="text-englishLight dark:text-englishDark text-4xl font-code">{text}</span>
            <span
                className={`text-4xl ml-1 text-englishLight dark:text-englishDark ${isFadeIn ? "animate-cursor-fade-in" : ""}`}>|</span>
        </div>
    );
};

export default TypeWriter;